package com.yonyou.le.unattended.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;



/**
 * Http请求工具类
 */
public class HttpRequestUtil {
	private static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);
	private static final String RESULT_STATUS="status";
	private static final String RESULT_CONTENT="result";
	/**
	 * http请求  GET方式
	 * @param url
	 * @return 服务器返回值 string
	 */
	public static String clientGET(String url) {
		RequestConfig defaultRequestConfig = RequestConfig.custom()
			    .setSocketTimeout(5000)
			    .setConnectTimeout(5000)
			    .setConnectionRequestTimeout(5000)
			    .build();
		CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
		
		HttpGet httpget = new HttpGet(url);
		CloseableHttpResponse response = null;
		String result=null;
		
		// 设置请求和传输超时时间5s,设置cookie策略
		/**
		 * 4.X版本的超时设置(4.3后已过时) HttpClient httpClient=new DefaultHttpClient();
		 * httpClient
		 * .getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT
		 * ,2000);//连接时间
		 * httpClient.getParams().setParameter(CoreConnectionPNames
		 * .SO_TIMEOUT,2000);//数据传输时间
		 */
		RequestConfig requestconfig = RequestConfig.custom()
				.setSocketTimeout(5000).setConnectTimeout(5000).build();
		httpget.setConfig(requestconfig);

		logger.info("Request URI:"+httpget.getURI());

		try {
			response = httpclient.execute(httpget);
			// 头信息
			HeaderIterator it = response.headerIterator();
			while (it.hasNext()) {
				System.out.println(it.next());
			}

			//判断访问的状态码
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: " + response.getStatusLine());
			}

			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result=EntityUtils.toString(entity);//请求结果
			}
			EntityUtils.consume(entity);
			response.close();
		} catch(ConnectException e){			
			logger.debug("连接失败！");
		} catch (UnsupportedEncodingException e) {
			logger.debug("连接失败！未识别编码");
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			logger.debug("连接失败！客户端协议异常");
			e.printStackTrace();
		} catch (IOException e) {
			logger.debug("连接失败！IO失败或连接超时");
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 基于httpclient 4.3+ 发送post请求
	 * <p> 连接超时返回NULL
	 * @param uri    请求地址
	 * @param args   key-value 形式
	 * @param encoding    参数编码
	 */

	public static String clientPOST(String uri, Map<String, String> args,
			String encoding) {
		String result = null;
		RequestConfig defaultRequestConfig = RequestConfig.custom()
			    .setSocketTimeout(10000)
			    .setConnectTimeout(10000)
			    .setConnectionRequestTimeout(10000)
			    .build();
		CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
		HttpPost httpPost = new HttpPost(uri);
		CloseableHttpResponse response = null;

		logger.info("Request URI:" + httpPost.getURI());

		// 将要POST的数据封包
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> temp : args.entrySet()) {
			NameValuePair nameValuePair = new BasicNameValuePair(temp.getKey(),
					temp.getValue());
			nvps.add(nameValuePair);
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
			response = httpclient.execute(httpPost);

			HttpEntity entity1 = response.getEntity();

			if (entity1 != null) {
				result = EntityUtils.toString(entity1, encoding);
			}
			EntityUtils.consume(entity1);

			response.close();
		} catch(ConnectException e){			
			logger.debug("连接失败！");
		} catch (UnsupportedEncodingException e) {
			logger.debug("连接失败！未识别编码");
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			logger.debug("连接失败！客户端协议异常");
			e.printStackTrace();
		} catch (IOException e) {
			logger.debug("连接失败！IO失败或连接超时");
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 基于httpclient 4.3+ 发送post请求,以json形式
	 * 
	 * @param uri    请求地址
	 * @param args   key-value 形式
	 * @param encoding    参数编码
	 * @return 
	 * <br/>status 0连接超时  1成功
	 * <br/>result 结果 
	 */

	public static String jsonPOST(String uri, String arg,
			String encoding){
		String result = null;
		Gson gson=new Gson();
		RequestConfig defaultRequestConfig = RequestConfig.custom()
			    .setSocketTimeout(5000)
			    .setConnectTimeout(5000)
			    .setConnectionRequestTimeout(5000)
			    .build();
		CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
		HttpPost httpPost = new HttpPost(uri);
		
		CloseableHttpResponse response = null;

		logger.debug("Request URI:" + httpPost.getURI());

		// 将要POST的数据封包

		try {
			StringEntity entity = new StringEntity(arg,"utf-8");//解决中文乱码问题    
			entity.setContentEncoding("UTF-8");    
			entity.setContentType("application/json");    
			httpPost.setEntity(entity);
			response = httpclient.execute(httpPost);

			HttpEntity entity1 = response.getEntity();

			if (entity1 != null) {
				result = EntityUtils.toString(entity1, encoding);
			}
			EntityUtils.consume(entity1);
			Map<String,String> argMap=new HashMap<String,String>();
			argMap.put("status", "1");
			argMap.put("result", result);
			result=gson.toJson(argMap);
			response.close();
			return result;
		} catch(ConnectException e){			
			logger.debug("连接失败！");
		} catch (UnsupportedEncodingException e) {
			logger.debug("连接失败！未识别编码");
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			logger.debug("连接失败！客户端协议异常");
			e.printStackTrace();
		} catch (IOException e) {
			logger.debug("连接失败！IO失败或连接超时");
			e.printStackTrace();
		}
		Map<String,String> argMap=new HashMap<String,String>();
		argMap.put("status", "0");
		argMap.put("result", "连接失败");
		result=gson.toJson(argMap);
		return result;
	}
	public static void main(String[] args) {
		// demo:代理访问
//		CarInfoData data = new CarInfoData();
//		data.setId("a1");
//		data.setOpcode("ZYD001");
//		data.setMaterial("AK47");
//		data.setCarno("京A 888888");
//		data.setCompany("山水集团");
//		data.setGrossweight("133");
//		data.setTareweight("12.08");
//		data.setNetweight("120.92");
//
//		Gson gs=new Gson();
		
//		String url = "http://10.1.211.153:8080/unattended/service/getWeight";
//		Map<String, String> argMap = new HashMap<String, String>();
//		argMap.put("deviceCode", "D0011");
//		String ret=HttpRequestUtil.clientPOST(url, argMap, "gbk");
//		System.out.println(ret);
//		
//		JSONObject jo=JSONObject.fromObject(ret);
//		System.out.println(jo.get("message"));
		
//		String url = "http://localhost:8080/unattended/service/enterOn";
//////		//String url = "http://20.2.32.11:91/service/leloginservice";
//
//		String ret=HttpRequestUtil.jsonPOST(url, gs.toJson(data), "gbk");
//		System.out.println(ret);
		//抬杆=========================
//		JSONObject jo=new JSONObject();
//		jo.put("deviceCode", "D001");
//		String url="http://172.18.1.74:8080/unattended_hardware/hardwareOperation/openGate";
//		String sr = null;
//		sr = HttpRequestUtil.jsonPOST(url, jo.toString(), "utf-8");
//		System.out.println(true);
//		System.out.println(sr);
		
		
		//取数======================================
//		CarInfoData md = new CarInfoData();
//		md.setCarno("京A 888888");
//		md.setId("1");
//		md.setMaterial("木头");
//		md.setOpcode("ZYD001");
//		
//		String url="http://localhost:8080/unattended/service/getWeight";
//		Map<String, String> argMap = new HashMap<String, String>();
//		argMap.put("carInfoData", new Gson().toJson(md));
//		String ret=HttpRequestUtil.clientPOST(url, argMap, "gbk");
//		System.out.println(ret);
		
//		String url="http://localhost:8080/unattended/APP/init";
//		Map<String, String> argMap = new HashMap<String, String>();
//		String ret=HttpRequestUtil.clientPOST(url, argMap, "gbk");
//		System.out.println(ret);
//		HttpRequestUtil.clientGET(url);
		
		//http://10.11.117.19:9090/unattended_hardware/hardwareOperation/showLed?deviceCode=a&ledText=b

//////////////LED		
//		String url="http://172.18.1.74:8080/unattended_hardware/hardwareOperation/showLed";
//		Map<String, String> argMap = new HashMap<String, String>();
//		argMap.put("deviceCode","D006");
//		argMap.put("ledText","GEFORCE GTX");
//		Gson gson = new Gson();
//		String result = HttpRequestUtil.jsonPOST(url, gson.toJson(argMap), "gbk");
//	    System.out.println(result);
	    
		String url="http://172.18.1.74:8080";
		String result = HttpRequestUtil.clientGET(url);
		System.out.println(result);
	}

}
